<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.8.0">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!--Description-->

    

    
        <meta name="description" content="AVAssetReaderAVAsserReader用于从AVAsset实例中读取媒体样本。通常会配置一个或多个AVAssetReaderOutput实例，并通过copyNextSampleBuffer方法可以访问音频样本和视频帧。AVAssetReaderOutput是一个抽象类，不过框架定义了3">
    

    <!--Author-->
    
        <meta name="author" content="Cyrus">
    

    <!--Open Graph Title-->
    
        <meta property="og:title" content="AVFoundation学习笔记十二 AVAssetReader AVAssetWriter">
    

    <!--Open Graph Description-->
    
        <meta property="og:description" content="AVAssetReaderAVAsserReader用于从AVAsset实例中读取媒体样本。通常会配置一个或多个AVAssetReaderOutput实例，并通过copyNextSampleBuffer方法可以访问音频样本和视频帧。AVAssetReaderOutput是一个抽象类，不过框架定义了3">
    

    <!--Open Graph Site Name-->
        <meta property="og:site_name" content="Cyrus的技术空间">

    <!--Type page-->
    
        <meta property="og:type" content="article">
    

    <!--Page Cover-->
    
    
        <meta property="og:image" content="http://cyrus_huang.gitee.io/bloghttp://www.codeblocq.com/assets/projects/hexo-theme-clean-blog/img/home-bg.jpg">
    

        <meta name="twitter:card" content="summary_large_image">

    

    
        <meta name="twitter:image" content="http://cyrus_huang.gitee.io/bloghttp://www.codeblocq.com/assets/projects/hexo-theme-clean-blog/img/home-bg.jpg">
    

    <!-- Title -->
    
    <title>AVFoundation学习笔记十二 AVAssetReader AVAssetWriter - Cyrus的技术空间</title>

    <!-- Bootstrap Core CSS -->
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/blog/css/style.css">

    <!-- Custom Fonts -->
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Gallery -->
    <link href="//cdnjs.cloudflare.com/ajax/libs/featherlight/1.3.5/featherlight.min.css" type="text/css" rel="stylesheet">

    <!-- Google Analytics -->
    


    <!-- favicon -->
    

</head>


<body>

    <!-- Menu -->
    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/blog/">Cyrus的技术空间</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav navbar-right">
                
                    <li>
                        <a href="/blog/">
                            
                                Home
                            
                        </a>
                    </li>
                
                    <li>
                        <a href="/blog/archives">
                            
                                Archives
                            
                        </a>
                    </li>
                
                    <li>
                        <a href="/blog/tags">
                            
                                Tags
                            
                        </a>
                    </li>
                
                    <li>
                        <a href="/blog/categories">
                            
                                Categories
                            
                        </a>
                    </li>
                
                    <li>
                        <a href="https://github.com/klugjo/hexo-theme-clean-blog">
                            
                                <i class="fa fa-github fa-stack-2x"></i>
                            
                        </a>
                    </li>
                
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>

    <!-- Main Content -->
    <!-- Page Header -->
<!-- Set your background image for this header in your post front-matter: cover -->

<header class="intro-header" style="background-image: url('http://www.codeblocq.com/assets/projects/hexo-theme-clean-blog/img/home-bg.jpg')">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <h1>AVFoundation学习笔记十二 AVAssetReader AVAssetWriter</h1>
                    
                    <span class="meta">
                        <!-- Date and Author -->
                        
                            Posted by Cyrus on
                        
                        
                            2018-11-12
                        
                    </span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

            <!-- Tags and categories -->
           
                <div class="col-lg-4 col-lg-offset-2 col-md-5 col-md-offset-1 post-tags">
                    
                        

<a href="/blog/categories/AVFoundation/">AVFoundation</a>

                    
                </div>
                <div class="col-lg-4 col-md-5 post-categories">
                    
                </div>
            

            <!-- Gallery -->
            

            <!-- Post Main Content -->
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <p><img src="http://cyrus_huang.gitee.io/blog/2018/11/12/AVFoundation学习笔记十二-AVAssetReader-AVAssetWriter/read_write.png" alt=""></p>
<h3 id="AVAssetReader"><a href="#AVAssetReader" class="headerlink" title="AVAssetReader"></a>AVAssetReader</h3><p>AVAsserReader用于从AVAsset实例中读取媒体样本。通常会配置一个或多个AVAssetReaderOutput实例，并通过copyNextSampleBuffer方法可以访问音频样本和视频帧。AVAssetReaderOutput是一个抽象类，不过框架定义了3个具本实例来从指定的AVAssetTrack中读取解码的媒体样本，从多音频轨道中读取混合输出，或者从多视频轨道中读取组合输出。一个资源读取器的内部通道都是以多线程的方式不断提取下一个可用样本的，这样可以在系统请求资源时最小化时延。</p>
<h3 id="AVAssetWriter"><a href="#AVAssetWriter" class="headerlink" title="AVAssetWriter"></a>AVAssetWriter</h3><p>AVAssetWriter是AVAssetReader对应的兄弟类，它用于对资源进行编码并将其写入到容器文件中。它由一个或多个AVAssetWriterInput对象配置，用于附加将包含要写入容器的媒体样本的CMSampleBuffer对象。AVAssetWriterInput被配置为可以处理指定的媒体类型，比如音频或视频，并且附加在其后的样本会在最终输出时生成一个独立的AVAssetTrack.当使用一个配置了处理视频样本的AVAssetWriterInput时，开发者会经常用到一个专门的适配器对象AVAssetWriterInputPixelBufferAdaptor.这个类在附加被包装为CVPixelBuffer对象的视频样本时提供最优性能。<br>AVAssetWriter可用于实时操作和离线操作两种情况，不过对于每个场景都有不同的方法将样本buffer添加到写入对象的输入中：</p>
<p><strong><em>实时</em></strong>：当处理实时资源时，比如从AVCaptureVideoDataOutput写入捕捉的样本时，AVAssetWriterInput应该令 expectsMediaDataInRealTime属性为YES来确保 readyForMoreMediaData值被正确计算。从实时资源写入数据优化了写入器，这样一来，与维持交错效果相比，快速写入样本具有更高的优先级。这一优化效果不错，视频和音频样本以大致相同的速率捕捉，传入数据自然交错。</p>
<p><strong><em>离线</em></strong>： 当从离线资源读取媒体资源时，比如从AVAssetReader读取样本buffer，在附加样本前仍然需要观察写入的readyForMoreMediaData属性的状态，不过可以使用requestMediaDataWhenReadyOnQueue：usingBlock:方法控制数据的提供。传到这个方法中的代码会随写入器输入准备附加更多的样本而不断被调用，添加样本时开发者需要检索数据并从资源中找到下一个样本进行添加。</p>
<p>读资源<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">AVAsset *asset = ...;</span><br><span class="line">    AVAssetTrack *track = [[asset tracksWithMediaType:AVMediaTypeVideo]firstObject];</span><br><span class="line">    AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:asset error:nil];</span><br><span class="line">    NSDictionary *readerOutputSettings = @&#123;</span><br><span class="line">                                           (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA)</span><br><span class="line">                                           &#125;;</span><br><span class="line">    AVAssetReaderOutput *trackOutput = [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:readerOutputSettings];</span><br><span class="line">    [assetReader addOutput:trackOutput];</span><br><span class="line">    [assetReader startReading];</span><br></pre></td></tr></table></figure></p>
<p>写资源<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">NSURL *outputURL = ...;</span><br><span class="line">    AVAssetWriter *assetWriter = [[AVAssetWriter alloc] initWithURL:outputURL fileType:AVFileTypeQuickTimeMovie error:nil];</span><br><span class="line">    NSDictionary *writerOutputSettings = @&#123;</span><br><span class="line">                                           AVVideoCodecKey : AVVideoCodecH264,</span><br><span class="line">                                           AVVideoWidthKey : @1280,</span><br><span class="line">                                           AVVideoHeightKey : @720,</span><br><span class="line">                                           AVVideoCompressionPropertiesKey : @&#123;</span><br><span class="line">                                                   AVVideoMaxKeyFrameIntervalKey : @1,</span><br><span class="line">                                                   AVVideoAverageBitRateKey : @10500000,</span><br><span class="line">                                                   AVVideoProfileLevelKey : AVVideoProfileLevelH264Main31</span><br><span class="line">                                                   &#125;</span><br><span class="line">                                           &#125;;</span><br><span class="line">    AVAssetWriterInput *writerInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo outputSettings:writerOutputSettings];</span><br><span class="line">    [assetWriter addInput:writerInput];</span><br><span class="line">    [assetWriter startWriting];</span><br></pre></td></tr></table></figure></p>
<p>从AVAssetReader拉取数据写入到文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">dispatch_queue_t dispatchQueue = dispatch_queue_create(&quot;com.tapharmonic.writerQueue&quot;, NULL);</span><br><span class="line">    [assetWriter startSessionAtSourceTime:kCMTimeZero];</span><br><span class="line">    [writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^&#123;</span><br><span class="line">        BOOL complete = NO;</span><br><span class="line">        while ([writerInput isReadyForMoreMediaData] &amp;&amp; !complete) &#123;</span><br><span class="line">            CMSampleBufferRef sampleBuffer = [trackOutput copyNextSampleBuffer];</span><br><span class="line">            if (sampleBuffer) &#123;</span><br><span class="line">                BOOL result = [writerInput appendSampleBuffer:sampleBuffer];</span><br><span class="line">                CFRelease(sampleBuffer);</span><br><span class="line">                complete = !result;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                [writerInput markAsFinished];</span><br><span class="line">                complete = YES;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (complete) &#123;</span><br><span class="line">            [assetWriter finishWritingWithCompletionHandler:^&#123;</span><br><span class="line">                AVAssetWriterStatus status = assetWriter.status;</span><br><span class="line">                if (status == AVAssetWriterStatusCompleted) &#123;</span><br><span class="line">                    //Handle success case</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    //Handle failure case</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;];</span><br></pre></td></tr></table></figure></p>


                
            </div>

            <!-- Comments -->
            
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    


                </div>
            
        </div>
    </div>
</article>

    <!-- Footer -->
    <hr>

<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                    

                    

                    
                        <li>
                            <a href="https://github.com/klugjo/hexo-theme-clean-blog" target="_blank">
                                <span class="fa-stack fa-lg">
                                    <i class="fa fa-circle fa-stack-2x"></i>
                                    <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                                </span>
                            </a>
                        </li>
                    

                    

                    

                    
                </ul>
                <p class="copyright text-muted">&copy; 2020 Cyrus<br></p>
                <p class="copyright text-muted">Original Theme <a target="_blank" href="http://startbootstrap.com/template-overviews/clean-blog/">Clean Blog</a> from <a href="http://startbootstrap.com/" target="_blank">Start Bootstrap</a></p>
                <p class="copyright text-muted">Adapted for <a target="_blank" href="https://hexo.io/">Hexo</a> by <a href="http://www.codeblocq.com/" target="_blank">Jonathan Klughertz</a></p>
                <p class="copyright text-muted"><a href="http://www.beian.miit.gov.cn">粤ICP备18110122号-1</a></p>
            </div>
        </div>
    </div>
</footer>


    <!-- After footer scripts -->
    
<!-- jQuery -->
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>

<!-- Bootstrap -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<!-- Gallery -->
<script src="//cdnjs.cloudflare.com/ajax/libs/featherlight/1.3.5/featherlight.min.js" type="text/javascript" charset="utf-8"></script>

<!-- Disqus Comments -->



</body>

</html>